package com.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class RabbitConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback{

    public static final String EXCHANGE_NAME = "exchange.test.priority";
    public static final String QUEUE_NAME = "queue.test.priority";
    public static final String ROUTING_KEY = "routing.test.priority";

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            log.info("消息成功发送到交换机");
        }else{
            log.info("消息发送到交换机失败");
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("消息从交换机理由到队列失败");
    }


    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(EXCHANGE_NAME, true, false);
    }

    @Bean
    public Queue queue(){
        //设置消息的优先级
        Map<String,Object> args = new HashMap<>();
        args.put("x-max-priority", 10);
        return new Queue(QUEUE_NAME, true, false, false, args);
    }


    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(directExchange()).with(ROUTING_KEY);
    }


}
